package com.itjiange.controller.user;

import cn.hutool.core.util.StrUtil;
import com.itjiange.service.FileMonitorService;
import com.itjiange.service.UserService;
import com.itjiange.service.impl.UserServiceImpl;
import com.wf.captcha.utils.CaptchaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.itjiange.constant.LoggerConstant.logger;

/**
 * 用户登录接口
 *
 * @author ItJiange
 * @date 2023/10/21
 */
@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    private FileMonitorService fileMonitorService = new FileMonitorService();
    private final UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String verCode = req.getParameter("verCode");
        // 2. 校验
        if (StrUtil.hasEmpty(username, password, verCode)) {
            logger.info("请求参数为空！");
            return;
        }
        if (!CaptchaUtil.ver(verCode, req)) {
            CaptchaUtil.clear(req);
            logger.info("验证码不正确！请重新登录！");
            resp.sendRedirect("/index.html");
            return;
        }
        boolean flag = userService.userLogin(username, password, req);
        if (!flag) {
            logger.info("登录失败！请重新登录！");
            resp.sendRedirect("/index.html");
            return;
        }
        logger.info("登陆成功！");
        resp.sendRedirect("/list.html");
    }

    @Override
    public void init() throws ServletException {
        fileMonitorService.startFileMonitor();
    }

    @Override
    public void destroy() {
        fileMonitorService.stopFileMonitor();
    }
}
